package com.uusoft.core.utils.db;

import java.util.Properties;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.DataSources;
import com.uusoft.core.exception.CommException;
import com.uusoft.core.utils.Assert;
import com.uusoft.core.utils.security.EncryptUtils;

/**
 * c3p0数据源提供类，系统默认使用此类提供数据库访问
 * @author shisheng.lian
 *
 */
public class C3p0DataSourceAdapter extends AbsDataSourceAdapter implements DataSourceAdapter {
	
	public static final String DRIVER_CLASS= "driverClass";
	public static final String JDBC_URL= "jdbcUrl";
	public static final String PASSWORD= "password";
	public static final String USER= "user";
	
	public void init() {
		Properties c3p0PropertiesGroup = getDSPropertiesGroup();
		String user = c3p0PropertiesGroup.getProperty(USER);
		String driverClass = c3p0PropertiesGroup.getProperty(DRIVER_CLASS);
		String jdbcUrl = c3p0PropertiesGroup.getProperty(JDBC_URL);
		String password = c3p0PropertiesGroup.getProperty(PASSWORD);
		
		Assert.nullString(user, "从配置文件中获取数据库连接用户名为空!");
		Assert.nullString(driverClass, "从配置文件中获取数据库驱动类为空！");
		Assert.nullString(jdbcUrl, "从配置文件中获取JDBC URL为空！");
		Assert.nullString(password, "从配置文件中获取数据库连接密码为空！");
		
		user = EncryptUtils.decryptSensitivity(user);
		password = EncryptUtils.decryptSensitivity(password);
		c3p0PropertiesGroup.put(USER, user);
		c3p0PropertiesGroup.put(PASSWORD, password);
		
		try {
			Class.forName(driverClass);
			DataSource unPooled = DataSources.unpooledDataSource(jdbcUrl, c3p0PropertiesGroup);
			setDs(DataSources.pooledDataSource(unPooled, c3p0PropertiesGroup));
		} catch (Exception e) {
			throw new CommException("建立数据源连接失败", e);
		}
	}
}
